//
//  MyInformationViewController.m
//  SsehMaster
//
//  Created by 杨阳 on 2018/8/3.
//  Copyright © 2018年 yinlong. All rights reserved.
//

#import "MyInformationViewController.h"
#import "MyInforHeaderImageTableViewCell.h"
#import "MyInforTableViewCell.h"
#import "SXPickPhoto.h"
#import "UIImage+FixOrientation.h"
#import "AddressSelectView.h"
#import "InformationModel.h"
#import <UIImageView+WebCache.h>

@interface MyInformationViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView * tableView;

@property (nonatomic,strong) UIButton * editButton;

@property (nonatomic,strong) NSMutableArray * dataSource;

@property (nonatomic,strong) SXPickPhoto * pickPhoto;

@property (nonatomic,strong) UIImage * profilePhotoImage;

@property (nonatomic,copy) NSString * nameStr, * phoneStr , *secondName , * secondPhone;

@property (nonatomic,copy) NSString * providerStr, * cityStr , *countryStr;

@property (nonatomic,strong) AddressSelectView * addressView;

@end

NSString * const MyInforHeaderImageTableViewCellID = @"MyInforHeaderImageTableViewCellID";
NSString * const MyInforTableViewCellID = @"MyInforTableViewCellID";

@implementation MyInformationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self baseSetting];
    [self layoutUI];
    
}

-(void)baseSetting{
    self.navigationItem.title = @"资料完善";
    self.view.backgroundColor = RGBColor(239, 238, 238);
    
    self.editButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.editButton.frame = CGRectMake(0, 0, 50, 44);
    self.editButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.editButton setTitle:@"编辑" forState:UIControlStateNormal];
    [self.editButton setTitle:@"保存" forState:UIControlStateSelected];
    [self.editButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.editButton addTarget:self action:@selector(editClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithCustomView:self.editButton];
    self.navigationItem.rightBarButtonItem = rightItem;
    
}
-(void)editClick:(UIButton *)button{
    
    if (button.selected) {
        if (self.profilePhotoImage != nil) {
            [self upLoadImage];
        }else{
            if (!kStringIsEmpty(self.nameStr)) {
                [self changNameAndImage:@""];
            }
        }
        
        if (!kStringIsEmpty(self.providerStr) ||!kStringIsEmpty(self.cityStr) ||!kStringIsEmpty(self.countryStr)||!kStringIsEmpty(self.secondName)||!kStringIsEmpty(self.secondPhone) ||!kStringIsEmpty(self.phoneStr)) {
            [self UpdateMemberWorker];
        }
        
    }
    button.selected = !button.selected;
    
    [self.tableView reloadData];
}

-(void)upLoadImage{
    
    //kUpdateMemberDetail  kUpdateMemberWorker
    [self showLoadingTitle:@"正在上传头像"];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    
    NSDate *datenow = [NSDate date];
    
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    
    [[QYNetManager sharedManager]upLoadSingeImage:@"https://member.yinweish.com/settingInterfaces/v1.0/uploadImg" parameters:nil andImage:self.profilePhotoImage andImageName:currentTimeString SuccessBlock:^(id responseObject) {
        [self hideLoading];
        if ([responseObject[@"status"] isEqualToString:@"ok"]) {
            [self changNameAndImage:[NSString stringWithFormat:@"%@",responseObject[@"data"]]];
        }else{
            [self showTipWithTitle:responseObject[@"error"]];
        }
    } Failure:^(NSError *error) {
        [self hideLoading];
        [self showErrorTipWithTitle:SsehPoolNetStr];
    }];
    
}

-(void)changNameAndImage:(NSString *)imageStr{
    
    NSString * imageUrlStr = [[NSString alloc]init];
    if (!kStringIsEmpty(imageStr)) {
        imageUrlStr = [NSString stringWithFormat:@"%@%@",kSsehImageIP,imageStr];
    }
    NSDictionary * par = @{@"member_id":[NSString emptyStr:DEF_PERSISTENT_GET_OBJECT(SsehUserID)],
                           @"member_token":[NSString emptyStr:DEF_PERSISTENT_GET_OBJECT(SsehUserToken)],
                           @"member_real_name":[NSString emptyStr:self.nameStr],
                           @"member_img":[NSString emptyStr:imageUrlStr],
                           @"member_nick_name":@"",
                           @"member_birthday":@"",
                           @"member_sex":@""
                           };
    
    [[QYNetManager sharedManager]POST:kUpdateMemberDetail parameters:par andApiTyp:SsehApiTypMain SuccessBlock:^(id responseObject) {
        
        if ([responseObject[@"status"] isEqualToString:@"ok"]) {
            if (!kStringIsEmpty(imageUrlStr)) {
                DEF_PERSISTENT_SET_OBJECT(imageUrlStr, Sseh_member_img);
            }
            self.profilePhotoImage = nil;
            if (!kStringIsEmpty(self.nameStr)) {
                NSDictionary * dic0 = @{@"title":@"姓名",
                                        @"content":[NSString emptyStr:self.nameStr],
                                        @"pl":@"姓名"};
                [self.dataSource replaceObjectAtIndex:0 withObject:dic0];
                DEF_PERSISTENT_SET_OBJECT([NSString emptyStr:self.nameStr], Sseh_member_real_name);
            }
            
            self.nameStr = nil;
            [self showTipWithTitle:@"修改成功"];
            [self.tableView reloadData];
        }else{
            [self showTipWithTitle:responseObject[@"error"]];
        }
        
    } Failure:^(NSError *error) {
        [self hideLoading];
        [self showErrorTipWithTitle:SsehPoolNetStr];
    }];
    
}

-(void)UpdateMemberWorker{
    
    NSDictionary * par = @{@"member_id":[NSString emptyStr:DEF_PERSISTENT_GET_OBJECT(SsehUserID)],
                           @"member_token":[NSString emptyStr:DEF_PERSISTENT_GET_OBJECT(SsehUserToken)],
                           @"member_name":[NSString emptyStr:self.secondName],
                           @"member_phone":[NSString emptyStr:self.secondPhone],
                           @"member_provider":[NSString emptyStr:self.providerStr],
                           @"member_city":[NSString emptyStr:self.cityStr],
                           @"member_country":[NSString emptyStr:self.countryStr]
                           };
    [[QYNetManager sharedManager]POST:kUpdateMemberWorker parameters:par andApiTyp:SsehApiTypGetOrders SuccessBlock:^(id responseObject) {
        
        if ([responseObject[@"status"] isEqualToString:@"ok"]) {
            [self showTipWithTitle:@"修改成功"];
            NSString * addS = [NSString stringWithFormat:@"%@ %@ %@",self.providerStr,self.cityStr,self.countryStr];
            if (!kStringIsEmpty(self.providerStr)) {
                NSDictionary * dic2 = @{@"title":@"地址",
                                        @"content":[NSString emptyStr:addS],
                                        @"pl":@"地址"};
                [self.dataSource replaceObjectAtIndex:2 withObject:dic2];
            }
            
            self.providerStr = nil;
            self.cityStr = nil;
            self.countryStr = nil;
            
            if (!kStringIsEmpty(self.secondName)) {
                NSDictionary * dic3 = @{@"title":@"紧急联系人",
                                        @"content":[NSString emptyStr:self.secondName],
                                        @"pl":@"紧急联系人"
                                        };
                [self.dataSource replaceObjectAtIndex:3 withObject:dic3];
            }
            if (!kStringIsEmpty(self.secondPhone)) {
                NSDictionary * dic4 = @{@"title":@"联系人号码",
                                        @"content":[NSString emptyStr:self.secondPhone],
                                        @"pl":@"联系人号码"};
                [self.dataSource replaceObjectAtIndex:4 withObject:dic4];
            }
            self.secondPhone = nil;
            self.secondName = nil;
            
            if (!kStringIsEmpty(self.phoneStr)) {
                NSDictionary * dic1 = @{@"title":@"手机号",
                                        @"content":[NSString emptyStr:self.phoneStr],
                                        @"pl":@"手机号"};
                [self.dataSource replaceObjectAtIndex:1 withObject:dic1];
            }
            self.phoneStr = nil;
            [self.tableView reloadData];
        }else{
            [self showTipWithTitle:responseObject[@"error"]];
        }
    } Failure:^(NSError *error) {
        [self hideLoading];
        [self showErrorTipWithTitle:SsehPoolNetStr];
    }];
    
}

-(void)layoutUI{
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor backGroudColorForView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    [self.tableView registerNib:[UINib nibWithNibName:@"MyInforHeaderImageTableViewCell" bundle:nil] forCellReuseIdentifier:MyInforHeaderImageTableViewCellID];
    [self.tableView registerNib:[UINib nibWithNibName:@"MyInforTableViewCell" bundle:nil] forCellReuseIdentifier:MyInforTableViewCellID];
    [self.view addSubview:self.tableView];
    
    UIView * headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 10)];
    headerView.backgroundColor = RGBColor(239, 238, 238);
    self.tableView.tableHeaderView = headerView;
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 6;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0 && self.editButton.selected) {
        [self aleShowView];
    }else if (indexPath.row == 3){
        if (self.editButton.selected) {
            __weak typeof (self)weakSelf = self;
            self.addressView.completeHandle = ^(NSDictionary *dic) {
                weakSelf.providerStr = dic[@"left"];
                weakSelf.cityStr = dic[@"mid"];
                weakSelf.countryStr = dic[@"right"];
                NSString * addressStr = [NSString stringWithFormat:@"%@ %@ %@",weakSelf.providerStr,weakSelf.cityStr,weakSelf.countryStr];
                NSDictionary * addressDic = @{@"title":@"地址",@"content":addressStr};
                [weakSelf.dataSource replaceObjectAtIndex:2 withObject:addressDic];
                [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:3 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
            };
            [self.addressView showView];
        }
        
    }
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        MyInforHeaderImageTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:MyInforHeaderImageTableViewCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.titleLabel.text = @"个人头像";
        
        
        if (self.profilePhotoImage != nil) {
            cell.rightImageView.image = self.profilePhotoImage;
        }else{
            [cell.rightImageView sd_setImageWithURL:[NSURL URLWithString:[NSString emptyStr:DEF_PERSISTENT_GET_OBJECT(Sseh_member_img)]] placeholderImage:[UIImage imageNamed:@"photop"]];
        }
        
        if (self.editButton.selected) {
            cell.rightShap.hidden = NO;
        }else{
            cell.rightShap.hidden = YES;
        }
        
        return cell;
    }else{
        MyInforTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:MyInforTableViewCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (self.editButton.selected) {
            
            if (indexPath.row == 2) {
                cell.rightShap.hidden = YES;
                cell.rightTF.userInteractionEnabled = NO;
            }else if (indexPath.row == 3){
                cell.rightShap.hidden = NO;
                cell.rightTF.userInteractionEnabled = NO;
            }else{
                cell.rightShap.hidden = NO;
                cell.rightTF.userInteractionEnabled = YES;
            }
            
        }else{
            cell.rightTF.userInteractionEnabled = NO;
            cell.rightShap.hidden = YES;
        }
        
        if (indexPath.row == 2 || indexPath.row == 5) {
            cell.rightTF.keyboardType = UIKeyboardTypePhonePad;
        }else{
            cell.rightTF.keyboardType = UIKeyboardTypeDefault;
        }
        
        [cell configData:self.dataSource[indexPath.row -1] andIndexPath:indexPath];
        
        cell.getTextBlock = ^(NSIndexPath *index, NSString *text) {
            switch (index.row) {
                case 1:
                    //姓名
                    self.nameStr = text;
                    break;
                case 2:
                    self.phoneStr = text;
                    //手机号
                    break;
                case 3:
                    //地址
                    break;
                case 4:
                    //紧急联系人
                    self.secondName = text;
                    break;
                case 5:
                    //联系人号码
                    self.secondPhone = text;
                    break;
                    
                default:
                    break;
            }
        };
        return cell;
    }
}

-(NSMutableArray *)dataSource{
    
    if (_dataSource == nil) {
        
        NSDictionary * dic0 = @{@"title":@"姓名",@"content":[NSString emptyStr:DEF_PERSISTENT_GET_OBJECT(Sseh_member_real_name)],@"pl":@"姓名"};
        NSDictionary * dic1 = @{@"title":@"手机号",@"content":[NSString emptyStr:DEF_PERSISTENT_GET_OBJECT(SsehUserAccount)],@"pl":@"手机号"};
        NSString * address = [NSString stringWithFormat:@"%@ %@ %@",[NSString emptyStr:self.infoModel.member_provider],[NSString emptyStr:self.infoModel.member_city],[NSString emptyStr:self.infoModel.member_country]];
        NSDictionary * dic2 = @{@"title":@"地址",@"content":[NSString emptyStr:address],@"pl":@"地址"};
        NSDictionary * dic3 = @{@"title":@"紧急联系人",@"content":[NSString emptyStr:self.infoModel.member_name],@"pl":@"紧急联系人"};
        NSDictionary * dic4 = @{@"title":@"联系人号码",@"content":[NSString emptyStr:self.infoModel.member_phone],@"pl":@"联系人号码"};
        
        _dataSource = [[NSMutableArray alloc]initWithCapacity:0];
        [_dataSource addObject:dic0];
        [_dataSource addObject:dic1];
        [_dataSource addObject:dic2];
        [_dataSource addObject:dic3];
        [_dataSource addObject:dic4];
        
    }
    return _dataSource;
}

#pragma 修改头像

- (void)aleShowView
{
    UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    //拍照：
    UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //打开相机
        [self.pickPhoto ShowTakePhotoWithController:self andWithBlock:^(NSObject *Data) {

            if ([Data isKindOfClass:[UIImage class]])
            {
                self.profilePhotoImage = [self getImageData:(UIImage *)Data];
                [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];

            }
        }];

    }];
    //相册
    UIAlertAction * act3 = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //打开相册
        [self.pickPhoto SHowLocalPhotoWithController:self andWithBlock:^(NSObject *Data) {
            if ([Data isKindOfClass:[UIImage class]])
            {
                self.profilePhotoImage = [self getImageData:(UIImage *)Data];
                [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
            }
        }];
    }];
    
    UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:nil message:@"选择上传方式" preferredStyle:UIAlertControllerStyleActionSheet];
    [aleVC addAction:act1];
    [aleVC addAction:act2];
    [aleVC addAction:act3];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:aleVC animated:YES completion:nil];
    });
    
}


//拍照按钮
-(void)cameraButOnClick{
    [self.pickPhoto.picker takePicture];
}
//取消拍照按钮
-(void)cancelBOnClick{
    
    [self.pickPhoto.picker  dismissViewControllerAnimated:YES completion:nil];
    
}

//图像处理
-(UIImage *)getImageData:(UIImage *)data{
    
    //原图
    //NSData * imageData1 = UIImageJPEGRepresentation(data, 1.0);
    //NSLog(@"原图：%lu",[imageData1 length]/1000);
    //对图片进行压处理 降低质量
    NSData * imageData = UIImageJPEGRepresentation(data, 0.2);
    //NSLog(@"压缩后：%lu",[imageData length]/1000);
    UIImage * newImage1 = [UIImage imageWithData:imageData];
    //对图片进行缩处理 缩小尺寸 降低分辨率
    newImage1 = [newImage1 compressImage:newImage1 toTargetWidth:600];
    
    return newImage1;
}

-(SXPickPhoto*)pickPhoto{
    if (!_pickPhoto) {
        _pickPhoto = [[SXPickPhoto alloc]init];
    }
    return _pickPhoto;
}

-(AddressSelectView *)addressView{
    
    if (_addressView == nil) {
        _addressView = [[AddressSelectView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT)];
    }
    return _addressView;
    
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = YES;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
